package com.zhang.second.day04;

import com.zhang.second.utils.IntegerSource;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * @title: ListState的使用：每来一条数据将历史数据升序,每隔10s输出最近10s内的历史数据
 * @author: zhang
 * @date: 2022/1/31 10:03
 */
public class Example2_2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new HistorySort())
                .print();

        env.execute();
    }

    public static class HistorySort extends KeyedProcessFunction<Integer, Integer, String> {

        private ListState<Integer> historyData;
        private ValueState<Long> timerTs;

        @Override
        public void open(Configuration parameters) throws Exception {
            historyData = getRuntimeContext().getListState(
                    new ListStateDescriptor<Integer>("history-data", Types.INT)
            );
            timerTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>("timer-ts", Types.LONG)
            );
        }

        @Override
        public void processElement(Integer value, Context ctx, Collector<String> out) throws Exception {
            historyData.add(value);
            long tenSecondLater = ctx.timerService().currentProcessingTime() + 10 * 1000L;
            if (timerTs.value() == null) {
                ctx.timerService().registerProcessingTimeTimer(tenSecondLater);
                timerTs.update(tenSecondLater);
            }
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<Integer, Integer, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
            ArrayList<Integer> arrayList = new ArrayList<>();
            for (Integer i : historyData.get()) {
                arrayList.add(i);
            }
            //清理缓存数据 节约内存
            historyData.clear();
            arrayList.sort(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o1 - o2;
                }
            });
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < arrayList.size() - 1; i++) {
                result.append(arrayList.get(i) + "->");
            }
            result.append(arrayList.get(arrayList.size() - 1));
            out.collect(result.toString());
            //清理保存定时器时间戳的状态变量
            timerTs.clear();
        }
    }
}
